package com.imdroid.carac.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.view.KeyEvent;
import android.widget.Toast;

import com.imdroid.carac.IMDroid;

/**
 * The basic activity which all the activity should be inherited from this.
 * 
 */
public abstract class BaseActivity extends Activity {
	/**
	 * Allow the back button.
	 */
	protected boolean allowBack = true;
	/**
	 * The messages
	 */
	public final static int MESSAGE_EXIT = 0x996;
	public final static int MESSAGE_IN_PROGRESS = 0x997;
	public final static int MESSAGE_TEXT = 0x997;
	public final static int MESSAGE_FINISH = 0x998;
	public final static int MESSAGE_ERROR = 0x999;
	/**
	 * The handler of message.
	 */
	protected Handler messageHandler;
	/**
	 * The wake lock to control the screen
	 */
	protected PowerManager.WakeLock wakeLock;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	public void onCreate(Bundle bdl) {
		super.onCreate(bdl);
		initHandler();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onResume()
	 */
	protected void onResume() {
		super.onResume();
		// 如果不在安防界面，则锁定屏幕常亮
		//if (wakeLock == null && !(this instanceof SecurityHomeActivity)) {
			// if (wakeLock == null ) {
		//	PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		//	wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
		//			this.getClass().getCanonicalName());
		//	wakeLock.acquire();
		//}

		// 如果不在安防界面，则 在SecurityService不响应报警
		// if (this instanceof SecurityHomeActivity)
		// SecurityService.setSecurityMode(false);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onPause()
	 */
	protected void onPause() {
		// 屏幕常亮解锁
		//if (wakeLock != null && wakeLock.isHeld()) {
		//	wakeLock.release();
		//	wakeLock = null;
		//}
		super.onPause();
	}

	/**
	 * 初始化Handler
	 */
	private void initHandler() {
		messageHandler = new Handler() {
			public void handleMessage(Message msg) {
				try {
					processedMessage(msg);
				} catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(IMDroid.getContext(), e.getMessage(),
							Toast.LENGTH_SHORT).show();
				}
			}
		};
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// Disable the "back" key
		if (!allowBack && keyCode == KeyEvent.KEYCODE_BACK)
			return true;
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * Show the alert dialog
	 * 
	 * @param message
	 *            The message
	 * @param ctx
	 *            The context
	 */
	protected void showAlert(int titleId, int stringId) {
		AlertDialog.Builder buidler = new AlertDialog.Builder(this);
		buidler.setTitle(titleId);
		buidler.setMessage(stringId);

		buidler.setPositiveButton("Ok", new OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
			}
		});
		buidler.show();
	}

	/**
	 * Show the alert dialog
	 * 
	 * @param message
	 *            The message
	 * @param ctx
	 *            The context
	 */
	protected void showAlert(String message) {
		AlertDialog.Builder buidler = new AlertDialog.Builder(this);
		buidler.setMessage(message);

		buidler.setPositiveButton("Ok", new OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
			}
		});
		buidler.show();
	}

	/**
	 * The method of process the message, it will implemented in the sub-class
	 * usually.
	 * 
	 * @param msg
	 *            the message the message
	 * 
	 * @throws Exception
	 */
	public void processedMessage(Message msg) throws Exception {
		switch (msg.what) {
		case MESSAGE_EXIT:
			this.finish();
		case MESSAGE_TEXT:
			Toast.makeText(IMDroid.getContext(), (String) (msg.obj),
					Toast.LENGTH_SHORT).show();
			break;
		case MESSAGE_ERROR:
			String errorMessage = ((Exception) (msg.obj)).getMessage();
			Toast.makeText(IMDroid.getContext(), errorMessage,
					Toast.LENGTH_SHORT).show();
			break;
		}

	}

	/**
	 * Send the message
	 * 
	 * @param what
	 *            The message to be send
	 * @param object
	 *            The object to be send
	 */
	protected void sendMessage(int what, Object object) {
		messageHandler.obtainMessage(what, object).sendToTarget();
	}

	/**
	 * Send the message
	 * 
	 * @param message
	 *            The message to be send
	 */
	protected void sendMessage(int what) {
		messageHandler.sendEmptyMessage(what);
	}

	/**
	 * Send the message
	 * 
	 * @param message
	 *            The message to be send
	 */
	protected void sendMessage(Message m) {
		messageHandler.sendMessage(m);
	}

	/**
	 * Run in progress, it need to implement in the sub-class
	 * 
	 * @throws Exception
	 */
	protected void actionInProgressBar(Object... params) throws Exception {

	}

	/**
	 * The ansyc task in progress bar
	 * 
	 */
	protected class InProgressBarTask extends
			AsyncTask<Object, Void, Exception> {
		ProgressDialog progressDialog;
		private Context context;
		private int titleText, messageText;

		/**
		 * The constructor with the context
		 * 
		 * @param context
		 *            the constructor with the context
		 * @param titleText
		 *            the title text
		 * @param messageText
		 *            the message text
		 */
		public InProgressBarTask(Context context, int titleText, int messageText) {
			this.context = context;
			this.titleText = titleText;
			this.messageText = messageText;

		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(context, context
					.getResources().getString(titleText), context
					.getResources().getString(messageText));
			progressDialog.show();
			progressDialog.setCancelable(true);

		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		protected Exception doInBackground(Object... params) {
			try {
				actionInProgressBar(params);
			} catch (Exception ex) {
				ex.printStackTrace();
				return ex;
			}
			return null;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		protected void onPostExecute(Exception result) {
			super.onPostExecute(result);
			progressDialog.dismiss();

			if (result != null) {
				String errorMessage = result.getMessage();
				Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT)
						.show();
			}
		}
	}
}
